import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { useChatStore } from '../store/chat';

// 指令常量
const COMMANDS = {
  // 心跳检测
  HEART_BEAT_REQUEST: 1000,
  HEART_BEAT_RESPONSE: 1001,

  // 登录
  LOGIN_REQUEST: 2000,
  LOGIN_RESPONSE: 2001,

  // 退出登录
  LOGOUT_REQUEST: 2002,
  LOGOUT_RESPONSE: 2003,

  // 消息
  MESSAGE_REQUEST: 3000,
  MESSAGE_RESPONSE: 3001
};

// 前缀长度
const PREFIX_LENGTH = 12;

export function useWebSocket() {
  const websocket = ref(null);
  const connected = ref(false);
  const router = useRouter();
  const chatStore = useChatStore();
  
  // 添加这些变量来保存用户信息
  let currentUsername = null;
  let currentTeamId = null;
  let isCustomerService = false;
  let currentUserId = null;
  
  // 添加计时器相关变量和函数
  let inactivityTimer = null;
  const inactivityTimeout = 30 * 60 * 1000; // 30分钟无操作自动断开
  
  // 添加心跳检测相关变量
  let heartbeatTimer = null;
  const heartbeatInterval = 5000; // 5秒发送一次心跳
  let reconnectTimer = null;
  const reconnectInterval = 5000; // 5秒尝试重连一次
  let reconnectAttempts = 0;
  const maxReconnectAttempts = 12; // 最多尝试重连12次（约1分钟）
  
  // 重置计时器函数
  const resetInactivityTimer = () => {
    if (!isCustomerService) return; // 只有客服端需要计时器
    
    if (inactivityTimer) {
      clearTimeout(inactivityTimer);
    }
    
    inactivityTimer = setTimeout(() => {
      console.log('长时间无操作，自动断开连接');
      closeWebSocket();
      router.push('/');
    }, inactivityTimeout);
  };
  
  // 启动计时器函数
  const startInactivityTimer = () => {
    if (!isCustomerService) return; // 只有客服端需要计时器
    resetInactivityTimer();
  };

  // 连接WebSocket
  const connect = () => {
    return new Promise((resolve, reject) => {
      if ('WebSocket' in window) {
        // 清除之前的重连定时器
        if (reconnectTimer) {
          clearTimeout(reconnectTimer);
          reconnectTimer = null;
        }
        
        websocket.value = new WebSocket(`ws://192.168.101.32:9999/chat`);
        websocket.value.binaryType = 'arraybuffer';
        
        // 连接成功回调
        websocket.value.onopen = () => {
          console.log("WebSocket连接成功");
          connected.value = true;
          reconnectAttempts = 0; // 重置重连尝试次数
          resolve(true);
        };
        
        // 接收消息回调
        websocket.value.onmessage = (event) => {
          const packet = decode(event.data);
          console.log("收到消息:", packet);
          
          // 根据指令类型处理消息
          handleMessage(packet);
        };
        
        // 连接错误回调
        websocket.value.onerror = (error) => {
          console.error("WebSocket连接错误", error);
          connected.value = false;
          
          // 尝试重连
          attemptReconnect();
          
          reject(error);
        };
        
        // 连接关闭回调
        websocket.value.onclose = () => {
          console.log("WebSocket连接关闭");
          connected.value = false;
          
          // 停止心跳
          stopHeartbeat();
          
          // 尝试重连
          attemptReconnect();
        };
        
        // 监听窗口关闭事件
        window.onbeforeunload = () => {
          closeWebSocket();
        };
      } else {
        alert('当前浏览器不支持WebSocket');
        reject(new Error('浏览器不支持WebSocket'));
      }
    });
  };
  
  // 尝试重新连接
  const attemptReconnect = () => {
    // 如果已经有重连定时器或者达到最大重连次数，则不再尝试
    if (reconnectTimer || reconnectAttempts >= maxReconnectAttempts) {
      if (reconnectAttempts >= maxReconnectAttempts) {
        console.error('达到最大重连次数，停止重连');
        alert('网络连接异常，请刷新页面重试');
      }
      return;
    }
    
    reconnectAttempts++;
    console.log(`尝试第 ${reconnectAttempts} 次重连...`);
    
    reconnectTimer = setTimeout(async () => {
      reconnectTimer = null;
      
      try {
        // 重新连接
        await connect();
        
        // 如果重连成功，重新登录
        if (connected.value && currentUsername) {
          const loginData = {
            username: currentUsername,
            teamId: currentTeamId || 0,
            isCustomerService: isCustomerService
          };
          
          const success = await login(loginData);
          
          if (success) {
            console.log('重连并重新登录成功');
            // 重新启动心跳
            startHeartbeat();
          } else {
            console.error('重连后登录失败');
            attemptReconnect();
          }
        }
      } catch (error) {
        console.error('重连失败:', error);
        attemptReconnect();
      }
    }, reconnectInterval);
  };

  // 处理接收到的消息
  const handleMessage = (packet) => {
    switch (packet.command) {
      case COMMANDS.HEART_BEAT_RESPONSE:
        // 心跳响应，不需要特殊处理
        console.log('收到心跳响应');
        break;
      case COMMANDS.LOGIN_RESPONSE:
        handleLoginResponse(packet);
        break;
      case COMMANDS.MESSAGE_RESPONSE:
        handleMessageResponse(packet);
        break;
      default:
        console.log("未知指令:", packet.command);
    }
  };

  // 处理登录响应
  const handleLoginResponse = (packet) => {
    if (packet.success) {
      // 保存用户信息
      localStorage.setItem('user', JSON.stringify(packet.user));
      chatStore.setCurrentUser(packet.user);
      currentUserId = packet.user.id; // 保存当前用户ID
      
      // 处理客服联系人信息
      if (packet.contact) {
        chatStore.setContact(packet.contact);
      }
      
      // 如果是客服，启动计时器
      if (isCustomerService) {
        startInactivityTimer();
      }
    } else {
      console.error("登录失败:", packet.message);
    }
  };

  // 处理消息响应
  const handleMessageResponse = (packet) => {
    console.log("收到消息响应:", packet);
    
    // 检查是否是自己发送的消息
    const isSelfMessage = packet.fromUserId === chatStore.currentUser.id;
    
    if (isSelfMessage) {
      // 如果是自己发送的消息，查找并替换临时消息
      const tempMessages = chatStore.messages.filter(msg => 
        msg.isTemp && 
        msg.fromUserId === packet.fromUserId && 
        msg.toUserId === packet.toUserId
      );
      
      if (tempMessages.length > 0) {
        // 替换最新的临时消息
        chatStore.replaceMessage(tempMessages[tempMessages.length - 1].id, {
          id: packet.id,
          content: packet.content,
          fromUserId: packet.fromUserId,
          toUserId: packet.toUserId,
          createdAt: packet.createdAt,
          updatedAt: packet.updatedAt,
          type: packet.type
        });
        return;
      }
    }
    
    // 如果不是自己发送的消息，或者没有找到临时消息，直接添加
    chatStore.addMessage({
      id: packet.id,
      content: packet.content,
      fromUserId: packet.fromUserId,
      toUserId: packet.toUserId,
      createdAt: packet.createdAt,
      updatedAt: packet.updatedAt,
      type: packet.type
    });
    
    // 如果是客服，并且当前没有选中联系人，自动选择发送消息的用户
    if (chatStore.currentUser && !chatStore.currentUser.isVisitor && 
        (!chatStore.currentContact || chatStore.currentContact.id !== packet.fromUserId)) {
      
      // 查找联系人
      const contact = chatStore.contacts.find(c => c.id === packet.fromUserId);
      if (contact) {
        chatStore.setContact(contact);
      } else {
        // 如果联系人不存在，添加到联系人列表
        chatStore.setContacts([
          ...chatStore.contacts,
          { id: packet.fromUserId, username: `用户${packet.fromUserId}` }
        ]);
        chatStore.setContact({ id: packet.fromUserId, username: `用户${packet.fromUserId}` });
      }
    }
    
    // 收到消息时重置计时器
    if (isCustomerService) {
      resetInactivityTimer();
    }
  };

  // 登录
  const login = (data) => {
    return new Promise((resolve) => {
      if (!websocket.value || websocket.value.readyState !== WebSocket.OPEN) {
        console.error("WebSocket未连接");
        resolve(false);
        return;
      }
  
      // 设置一个回调处理登录响应
      const loginResponseHandler = (event) => {
        const packet = decode(event.data);
        if (packet.command === COMMANDS.LOGIN_RESPONSE) {
          websocket.value.removeEventListener('message', loginResponseHandler);
          
          if (packet.success) {
            // 保存用户信息到本地存储
            localStorage.setItem('user', JSON.stringify(packet.user));
            chatStore.setCurrentUser(packet.user);
            currentUserId = packet.user.id; // 保存当前用户ID
            
            // 处理联系人信息
            if (packet.contacts && Array.isArray(packet.contacts)) {
              chatStore.setContacts(packet.contacts);
            }
            
            // 处理客服联系人信息
            if (packet.contact) {
              chatStore.setContact(packet.contact);
            }
            
            resolve(true);
          } else {
            console.error("登录失败:", packet.message);
            resolve(false);
          }
        }
      };
      
      // 添加临时事件监听器
      websocket.value.addEventListener('message', loginResponseHandler);
      
      // 发送登录请求
      sendPacket(createPacket(data, COMMANDS.LOGIN_REQUEST));
      
      // 启动心跳检测
      startHeartbeat();
    });
  };

  // 发送消息
  const sendMessage = (content, toUserId) => {
    if (!websocket.value || websocket.value.readyState !== WebSocket.OPEN) {
      console.error('WebSocket未连接');
      // 尝试重新连接
      if (currentUsername && currentTeamId) {
        console.log('尝试重新连接WebSocket...');
        initWebSocket(currentUsername, currentTeamId, isCustomerService);
      }
      return false;
    }
    
    try {
      // 创建消息对象
      const messageData = {
        content: content,
        type: 1,
        toUserId: toUserId
      };
      
      // 发送消息
      sendPacket(createPacket(messageData, COMMANDS.MESSAGE_REQUEST));
      
      // 添加临时消息到本地
      const tempId = Date.now();
      chatStore.addMessage({
        id: tempId,
        content: content,
        fromUserId: currentUserId,
        toUserId: toUserId,
        createdAt: new Date().toISOString(),
        isTemp: true
      });
      
      // 如果是客服，重置计时器
      if (isCustomerService) {
        resetInactivityTimer();
      }
      
      return true;
    } catch (error) {
      console.error('发送消息失败:', error);
      return false;
    }
  };

  // 关闭WebSocket连接
  const closeWebSocket = () => {
    // 停止心跳检测
    stopHeartbeat();
    
    // 停止重连尝试
    if (reconnectTimer) {
      clearTimeout(reconnectTimer);
      reconnectTimer = null;
    }
    
    if (websocket.value) {
      websocket.value.close();
    }
    
    // 清除计时器
    if (inactivityTimer) {
      clearTimeout(inactivityTimer);
      inactivityTimer = null;
    }
  };

  // 启动心跳检测
  const startHeartbeat = () => {
    // 先停止之前的心跳检测
    stopHeartbeat();
    
    // 启动新的心跳检测
    heartbeatTimer = setInterval(() => {
      if (websocket.value && websocket.value.readyState === WebSocket.OPEN) {
        console.log("发送心跳");
        sendPacket(createPacket({}, COMMANDS.HEART_BEAT_REQUEST));
      } else {
        // WebSocket未连接，尝试重连
        console.log("心跳检测发现WebSocket未连接，尝试重连");
        attemptReconnect();
      }
    }, heartbeatInterval);
    
    console.log("心跳检测已启动");
  };
  
  // 停止心跳检测
  const stopHeartbeat = () => {
    if (heartbeatTimer) {
      clearInterval(heartbeatTimer);
      heartbeatTimer = null;
      console.log("心跳检测已停止");
    }
  };

  // 发送数据包
  const sendPacket = (packet) => {
    if (websocket.value && websocket.value.readyState === WebSocket.OPEN) {
      websocket.value.send(encode(packet));
      return true;
    }
    return false;
  };

  // 创建数据包
  const createPacket = (data, command) => {
    return Object.assign({
      version: 1,
      command: command
    }, data);
  };

  // 编码
  const encode = (packet) => {
    const bytes = stringToBytes(JSON.stringify(packet));
    const buffer = new ArrayBuffer(PREFIX_LENGTH + bytes.length);
    if (buffer.byteLength !== PREFIX_LENGTH + bytes.length) {
      console.log('编码分配内存失败，内存不足');
      return null;
    }
    const dataView = new DataView(buffer);

    dataView.setInt32(0, 0x12345678);
    dataView.setInt8(4, packet.version);
    dataView.setInt8(5, 1); // 写死1表示json序列化
    dataView.setInt16(6, packet.command);
    dataView.setInt32(8, bytes.length);
    for (let i = PREFIX_LENGTH; i < bytes.length + PREFIX_LENGTH; i++) {
      dataView.setUint8(i, bytes[i - PREFIX_LENGTH]);
    }
    return dataView.buffer;
  };

  // 解码
  const decode = (buffer) => {
    const dataView = new DataView(buffer);
    const length = dataView.getInt32(8);
    const bytes = [];
    for (let i = PREFIX_LENGTH; i < length + PREFIX_LENGTH; i++) {
      bytes[i - PREFIX_LENGTH] = dataView.getUint8(i);
    }
    const json = bytesToString(bytes);
    return JSON.parse(json);
  };

  // 字符串转byte数组
  const stringToBytes = (str) => {
    const bytes = [];
    let c;
    const len = str.length;
    for (let i = 0; i < len; i++) {
      c = str.charCodeAt(i);
      if (c >= 0x010000 && c <= 0x10FFFF) {
        bytes.push(((c >> 18) & 0x07) | 0xF0);
        bytes.push(((c >> 12) & 0x3F) | 0x80);
        bytes.push(((c >> 6) & 0x3F) | 0x80);
        bytes.push((c & 0x3F) | 0x80);
      } else if (c >= 0x000800 && c <= 0x00FFFF) {
        bytes.push(((c >> 12) & 0x0F) | 0xE0);
        bytes.push(((c >> 6) & 0x3F) | 0x80);
        bytes.push((c & 0x3F) | 0x80);
      } else if (c >= 0x000080 && c <= 0x0007FF) {
        bytes.push(((c >> 6) & 0x1F) | 0xC0);
        bytes.push((c & 0x3F) | 0x80);
      } else {
        bytes.push(c & 0xFF);
      }
    }
    return bytes;
  };

  // byte数组转字符串
  const bytesToString = (bytes) => {
    if (typeof bytes === 'string') {
      return bytes;
    }
    let str = '';
    const _arr = bytes;
    for (let i = 0; i < _arr.length; i++) {
      const one = _arr[i].toString(2);
      const v = one.match(/^1+?(?=0)/);
      if (v && one.length === 8) {
        const bytesLength = v[0].length;
        let store = _arr[i].toString(2).slice(7 - bytesLength);
        for (let st = 1; st < bytesLength; st++) {
          store += _arr[st + i].toString(2).slice(2);
        }
        str += String.fromCharCode(parseInt(store, 2));
        i += bytesLength - 1;
      } else {
        str += String.fromCharCode(_arr[i]);
      }
    }
    return str;
  };

  // 初始化WebSocket并连接
  const initWebSocket = (username, teamId, customerService = false) => {
    return new Promise(async (resolve, reject) => {
      try {
        // 保存用户信息
        currentUsername = username;
        currentTeamId = teamId;
        isCustomerService = customerService;
        
        // 连接WebSocket
        await connect();
        
        // 登录
        const loginData = {
          username: username,
          teamId: teamId || 0,
          isCustomerService: customerService
        };
        
        const success = await login(loginData);
        
        // 如果是客服，启动计时器
        if (success && customerService) {
          startInactivityTimer();
        }
        
        resolve(success);
      } catch (error) {
        console.error('WebSocket初始化失败:', error);
        reject(error);
      }
    });
  };

  return {
    connect,
    login,
    sendMessage,
    closeWebSocket,
    connected,
    initWebSocket,
    resetInactivityTimer,
    startInactivityTimer
  };
}
